#include "head.h"

int msqid;
key_t clients[32];
int client_count;

void sigint(int signo) {
	if (msgctl(msqid, IPC_RMID, NULL) == -1) {
		perror("msgctl sigint server");
		exit(1);
	} else {
		printf("Odlaczanie klientow\n");
		int i;
		for (i = 0; i < client_count; i++) {
			
		}
		printf("Zamykanie kolejki\n");
		return;
	}
}

int main(int argc, char ** argv) {
	if (argc != 2) {
		printf("Złe wywołanie. Poprawne wywołanie: ./zad1a.o <path>\n");
		return 1;
	}
	if (signal(SIGINT, sigint) == SIG_ERR) {
		perror("signal server");
		return -1;
	}
	key_t key;
	int id = 64;
	if ((key = ftok(argv[1], id)) == -1) {
		perror("server ftok");
		return 2;
	}
	if ((msqid = msgget(key, IPC_CREAT | 0666)) == -1) {
		perror("server msgget");
		return 3;
	}
	struct msqid_ds queue_info;
	if (msgctl(msqid, IPC_STAT, &queue_info) == -1) {
		perror("server msgctl");
		return 4;
	}
	struct message mess;
	while (1) {
		int i;
		sleep(1);
		if (msgrcv(msqid, &mess, sizeof(struct message), 0, IPC_NOWAIT) > 0) {
			if (mess.type == 1) {
				int client = atoi(mess.message);
				clients[client_count++] = client;
			}
		}
		for (i = 0; i < client_count; i++) {
			if (msgrcv(clients[i], &mess, sizeof(struct message), 2, IPC_NOWAIT) >= 0) {
				mess.type = 3;
				for (i = 0; i < client_count; i++) {
					if (msgsnd(clients[i], &mess, sizeof(struct message), 0) == -1) {
						perror("msgsend");
					}
				}
			}
		}
	}
	return 0;
}
